from rest_framework.response import Response
from rest_framework.decorators import api_view
from rest_framework import status


from .serializers import DataSourceSerializer
from myapp.models import DataSource

@api_view(['GET'])
def get_data(request):
    data = {
        "message": "Hello, World!"
    }
    return Response(data)

@api_view(['GET', 'POST'])
def datasource_list(request):
    if request.method == 'POST':
        serializer = DataSourceSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=201)
        return Response(serializer.errors, status=400)
    if request.method == 'GET':
        dataSource = DataSource.objects.all()
        serializer = DataSourceSerializer(dataSource, many=True)
        return Response(serializer.data)
    
@api_view(['GET', 'PUT', 'DELETE'])
def datasource_detail(request,id):
    try:
        datasource = DataSource.objects.get(id=id);
    except DataSource.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)
    if request.method == 'GET':
        serializer = DataSourceSerializer(datasource)
        return Response(serializer.data)
    if request.method == 'PUT':
        serializer = DataSourceSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=201)
        return Response(serializer.errors, status=400)
    if request.method == 'DELETE':
        datasource.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)